package com.ycy.chuwenuniapp.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class HmacSha256Util {
    public static String hmacSha256(String sessionKey, String message) {
        try {
            // Mac mac = Mac.getInstance("HmacSHA256");
            // SecretKeySpec secretKeySpec = new SecretKeySpec(sessionKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            // mac.init(secretKeySpec);
            // byte[] signatureBytes = mac.doFinal(message.getBytes(StandardCharsets.UTF_8));
            // return bytesToHex(signatureBytes);

            // byte[] keyBytes = Base64.getDecoder().decode(sessionKey);
            byte[] keyBytes = Base64.decodeBase64(sessionKey);
            Mac mac = Mac.getInstance("HmacSHA256");
            SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "HmacSHA256");
            mac.init(keySpec);
            byte[] signatureBytes = mac.doFinal(message.getBytes("UTF-8"));
            return Base64.encodeBase64String(signatureBytes);
        } catch (Exception e) {
            throw new RuntimeException("Failed to generate HMAC-SHA256 signature", e);
        }
    }

    public static JSONObject decryptWeChatUserData(String encryptedData, String sessionKey, String iv) {
        try {
            byte[] encryptedDataBytes = Base64.decodeBase64(encryptedData);
            byte[] sessionKeyBytes = Base64.decodeBase64(sessionKey);
            byte[] ivBytes = Base64.decodeBase64(iv);

            SecretKeySpec secretKeySpec = new SecretKeySpec(sessionKeyBytes, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);

            byte[] decryptedDataBytes = cipher.doFinal(encryptedDataBytes);
            String decryptedData = new String(decryptedDataBytes, "UTF-8");

            return JSON.parseObject(decryptedData);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // JSONObject userData = WeChatUtil.decryptWeChatUserData(encryptedData, sessionKey, iv);
    // String nickName = userData.getString("nickName");
    // String avatarUrl = userData.getString("avatarUrl");

    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}
